import React, { FC, useEffect, useState, useRef } from 'react'
import { Button, Drawer, message, Modal, Table, Select, Space } from 'antd'
import { EditableProTable, ProColumns } from '@ant-design/pro-table';
import { getModuleList, deleteModule, updateModule, addModule } from '@/services/proModule'
import { getMicroList } from '@/services/proMicro';

interface ModuleConfigProps {
  onClose:any,
  visible:boolean,
  projectId:string,
  isMicro:boolean
}

const ModuleConfig: FC<ModuleConfigProps> = (props) => {

  const ref = useRef<any>();

  const {onClose, visible, projectId,isMicro } = props
  const [editableKeys, setEditableRowKeys] = useState<any>([]);
  const [moduleList, setModuleList] = useState<any>([]);
  const [microList, setMicroList] = useState<any>([]);
  useEffect(() => {
    if (visible && isMicro) {
      // 获取微服务列表
      getMicroList({project_id:projectId}).then((res) => {
        if (res.code === 10000) {
          setMicroList(res.data);
        }
      })
    }
  }, [projectId, visible])

  const columns: ProColumns<any>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '显示名称',
      dataIndex: 'show_name',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '简介',
      dataIndex: 'description',
      hideInSearch:true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width:150,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  if(isMicro) {
    columns.unshift(
      {
        title: '微服务',
        dataIndex: 'micro_id',
        valueType: 'select',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必选项',
            },
          ],
        },
        renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
          return <Select placeholder="请选择微服务" style={{width: '100%'}}>
            {microList.map((v: any) => {
              return (
                <Select.Option key={v.id} value={v.id}>
                  {v.name}
                </Select.Option>
              );
            })}
          </Select>;
        },
        render: (_, record) => {
          let name = '-';
          const detail: any = microList.filter((value: any) => value.id == record.micro_id);
          if (detail.length > 0) {
            name = detail[0].name;
          }
          return <span>{name}</span>
        },
      },
    )
  }

  return (
    <>
      <Drawer
        title="模块管理"
        width={800}
        onClose={() => onClose(false)}
        visible={visible}
        bodyStyle={{ paddingBottom: 80,backgroundColor:'#f0f2f5' }}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={() => onClose(false)} type="primary">
              关闭
            </Button>
          </div>
        }>
        <EditableProTable
          actionRef={ref}
          rowKey="id"
          columns={columns}
          request={ async (val) => getModuleList({...val,project_id:projectId}).then((res) => {
            setModuleList(res.data);
            return res;
          })}
          value={moduleList}
          headerTitle="模块列表"
          search={isMicro ? {filterType:'query'} : false}
          options={{search: false}}
          editable={{
            editableKeys,
            onSave: async (key:any,val:any) => {
              delete val.index;
             if (val.id) {
               delete val.create_time;
               await updateModule(val).then((res) => {
                 if (res.code === 10000) {
                   ref.current.reload();
                   message.success('修改成功！')
                 }
               })
             }else {
               val.project_id = projectId;
               await addModule(val).then((res) => {
                 if (res.code === 10000) {
                   ref.current.reload();
                   message.success('添加成功！')
                 }
               })
             }
            },
            onDelete: async (value:any) => deleteModule({id:value}).then((res) => {
              if (res.code === 10000) {
                message.success('删除成功！')
                ref.current.reload();
              }
            }),
            onChange: setEditableRowKeys,
          }}
        />
      </Drawer>
    </>
  )
}

export default ModuleConfig;
